using System;
using Lichtspiel.Math;
using Lichtspiel.Utility;

namespace Lichtspiel.ECSystem.Behaviors
{
    public class RotateTo : Behavior
    {
        private TimeSpan length;
        private Interpolator<float>.InterpolationMethod interpMethod;
        private Interpolator<float> interpolator;
        private float start;
        private float target;

        public RotateTo(float targetDegrees, TimeSpan length)
            : this(targetDegrees, length, InterpolationHelper.Linear) { }

        public RotateTo(float targetDegrees, TimeSpan length, Action finished)
            : this(targetDegrees, length, InterpolationHelper.Linear, finished) { }

        public RotateTo(float targetDegrees, TimeSpan length, Interpolator<float>.InterpolationMethod interpMethod) 
            : this(targetDegrees, length, interpMethod, null) {}

        public RotateTo(float targetDegrees, TimeSpan length, Interpolator<float>.InterpolationMethod interpMethod, Action finished) 
            : base(finished) {
            this.length = length;
            target = targetDegrees;
            this.interpMethod = interpMethod;
        }

        protected override void Initialize() {
            start = owner.Rotation;

            interpolator = new Interpolator<float>(start, target, length, interpMethod,
                                                    i => owner.Rotation = i.Value, i => BehaviorFinished());
        }

        public override void Update(GameTime time) {
            base.Update(time);

            interpolator.Update(time);
        }

        internal override void Stop() {
            base.Stop();

            interpMethod = null;
            if (interpolator != null) {
                interpolator.Stop();
            }
            interpolator = null;
        }
    }
}